<template>
  <div class="app-container customer-div">
    <vxe-grid ref='customerListGrid' v-bind="gridOptions"  size="mini" :loading="listLoading">
      <template #form>
        <!--搜索-->
        <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
          <el-form-item label="客户名称：">
            <el-autocomplete
              clearable
              class="inline-input"
              value-key="customerName"
              :fetch-suggestions="querySearch"
              v-model="listQuery.customerName"
              placeholder="请输入内容"
              @select="handleSelectCustomerName"
              :trigger-on-focus="false"
            ></el-autocomplete>
          </el-form-item>
          <el-form-item label="最近跟进时间：">
            <el-date-picker
              v-model="listQuery.lastTrackingTime"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="最近成交时间：">
            <el-date-picker
              v-model="listQuery.lastOrderTime"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="未跟进天数：">
            <el-select clearable v-model="listQuery.notTrackingTime">
              <el-option :key="7" label="7天" :value="7"></el-option>
              <el-option :key="15" label="15天" :value="15"></el-option>
              <el-option :key="30" label="30天" :value="30"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="负责人：">
            <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
              <el-option
                v-for="item in userOptionList"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="客户分类：">
            <el-select v-model="listQuery.customerNewType" placeholder="请选择" clearable>
              <el-option
                v-for="item in customerTypeList"
                :key="item.cddValue"
                :label="item.cddValue"
                :value="item.cddValue">
              </el-option>
            </el-select>
          </el-form-item>

<!--          <el-form-item label="临近带宽末期：">-->
<!--            <el-select v-model="listQuery.isEndMonth" class="input-width" style="width:195px" placeholder="请选择" clearable>-->
<!--              <el-option label="是" :value="1"></el-option>-->
<!--              <el-option label="不限" :value="0"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->

           <el-form-item label="所在地区："  v-if="areaList&&areaList.length>0">
            <el-select v-model="listQuery.areaId1" placeholder="请选择省" @change="changeAreaId1" style="width:120px" clearable>
              <el-option v-for="item in areaList"  :key="item.areaId" :label="item.areaName"  :value="item.areaId" ></el-option>
            </el-select>
            <el-select v-model="listQuery.areaId2" placeholder="请选择市" @change="changeAreaId2" v-if="listQuery.areaId1" style="width:120px" clearable>
              <el-option v-for="item in areaList[areaIndex1]['areaChildList']"  :key="item.areaId" :label="item.areaName"  :value="item.areaId"></el-option>
            </el-select>
            <el-select v-model="listQuery.areaId2" placeholder="请选择市" @change="changeAreaId2" v-else style="width:120px" clearable></el-select>
            <el-select v-model="listQuery.areaId3" placeholder="请选择区" style="width:120px" v-if="listQuery.areaId2" clearable>
              <el-option v-for="item in areaList[areaIndex1]['areaChildList'][areaIndex2]['areaChildList']"  :key="item.areaId" :label="item.areaName"  :value="item.areaId"></el-option>
            </el-select>
            <el-select v-model="listQuery.areaId3" placeholder="请选择区" v-else style="width:120px"></el-select>
           </el-form-item>

           <el-form-item label="创建时间：">
            <el-date-picker
              v-model="listQuery.customerCreateTime"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="负责时间：">
            <el-date-picker
              v-model="listQuery.chargeStartTime"
              type="daterange"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="产品线：">
            <el-select v-model="listQuery.goodsLineId" filterable clearable>
              <el-option
                v-for="(item,index) in goodsLineList"
                :key="index"
                :label="item.cddValue"
                :value="item.cddId">
             </el-option>
            </el-select>
          </el-form-item>

<!--          <el-form-item label="联系人电话：">-->
<!--            <el-input v-model="listQuery.contactMobile" clearable style="width:200px;"></el-input>-->
<!--          </el-form-item>-->

          <el-form-item label="客户性质：">
            <el-select v-model="listQuery.customerQuality" clearable>
              <el-option v-for="item in customerQualityList"  :key="item.cddId"  :value="item.cddId" :label="item.cddValue"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="流转类型：">
            <el-select v-model="listQuery.moveType" clearable>
              <el-option value="unTrackingOutTime" label="未跟进客户超期"></el-option>
              <el-option value="unOrderOutTime" label="未成交客户超期"></el-option>
<!--              <el-option value="orderOutTime" label="成交客户超期"></el-option>-->
            </el-select>
          </el-form-item>

          <el-form-item label="规模性质：">
            <el-select v-model="listQuery.newNature" clearable >
              <el-option v-for="(item,index) in newNatureList" :key="index" :value="item" :label="item"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              @click="handleSearchList()"
              type="primary">
              查询
            </el-button>
            <el-button
              @click="moreyc"
              type="primary">
              批量延长
            </el-button>
          </el-form-item>
        </el-form>
      </template>
      <template #pager>
        <div style="overflow: hidden">
          <div class="pagination-container">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes,prev, pager, next,jumper"
              :current-page.sync="listQuery.pageNum"
              :page-size="listQuery.pageSize"
              :page-sizes="[10,15,20]"
              :total="count">
            </el-pagination>
          </div>
        </div>
      </template>
      <template #toolbar_buttons>
        <div>
          <el-radio-group  size="small" v-model="listQuery.stepId" @change="handleSearchList">
            <el-radio-button label="" >全部({{num[0]}})</el-radio-button>
            <el-radio-button :label="item.stepId" v-for="item in stepList" :key="item.stepId">{{ item.stepName }}({{num[item.stepId]}})</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <template #num1_default="{ row, rowIndex }">
        <el-link @click="toDetail(row)" type="primary">
          {{row.customerName}}
        </el-link>
      </template>

      <template #num2_default="{ row, rowIndex }">
        <div v-for="(item,index) in row.sonName" :key="index">
          {{ item }}
        </div>
      </template>

      <!-- <template #num3_default="{ row, rowIndex }">
        <span>{{row.applyState | fifApply}}</span>
      </template> -->

      <template #num4_default="{ row, rowIndex }">
        <el-button
          type="text"
          size="mini"
          @click="showQuit(row,'one')">转移
        </el-button>
        <el-button
          type="text"
          size="mini"
          @click="delay(row)">延长
        </el-button>
      </template>
    </vxe-grid>
     <!-- 转移 -->
    <cmsTransfer ref='cmsTransfer' @update="getList"></cmsTransfer>
  </div>
</template>
<script>
import {
  getCustomerOption,getConfigList
} from '@/api/partner'
import {
  trackingCustomerList,getCustomerInfoAPI,delayCustomer
} from '@/api/company'
import { mapGetters } from 'vuex'
import cmsTransfer from '@/views/cms/components/cmsTransfer.vue';
const defaultListQuery={
  pageNum: 1,
  pageSize: 10,
  type:'',
  tab: '',
  isToday:0,
  lastTrackingTime: null,
  lastOrderTime:null,
  customerName:null,
  isOrder:null,
  stepId:'',
  notTrackingTime: '',
  userId:'',
  newLevel:'',
  isEndMonth: '',//是否临近宽带
  areaId1: '',//省ID
  areaId2: '',//市
  areaId3: '',//区
  customerCreateTime:[],//创建时间
  chargeStartTime: [],//负责时间搜索
  goodsLineId:'',//产品线ID搜索
  contactMobile: '',//联系人的电话搜索
  customerQuality: '',//客户性质
  moveType:'',
  customerNewType:'',
  newNature:''
};
const defaultForm={
  deliverId: '',
  goodsReceipt: [],
  goodsReceiptRemark: '',
  goodsReceiptDate:''
};
const defaultyqForm={
  dataId: '',
  applyReason: '',
  type: '',
  customerName:'',
  time:''
};
const defaultsqForm={
  dataId: '',
  customerName:'',
  applyReason: '',
};
export default {
  name: "transferList",
  props: {
    stepList:{
      type: Array,
      default:()=>[]
    },
    areaList: {
      type: Array,
      default: () => []
    },
    customerLevelList: {
      type: Array,
      default: () => []
    },
    goodsLineList: {
      type: Array,
      default: () => []
    },
    userOptionList:{
      type: Array,
      default:()=>[]
    },
    customerQualityList: {
      type: Array,
      default:()=>[]
    }
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value <= 0) {
        callback(new Error('天数不得小于0'));
      } else {
        callback();
      }
    };
    return {
      listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
      areaIndex1: null,
      areaIndex2: null,
      tableData: [],
      count: 0,
      listLoading: false,
      multipleSelection: [],
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible3: false,
      form: JSON.parse(JSON.stringify(defaultForm)),
      btnLoading: false,
      btnLoading3: false,
      yqForm: JSON.parse(JSON.stringify(defaultyqForm)),
      sqForm: JSON.parse(JSON.stringify(defaultsqForm)),
      num: {},
      gridOptions: {
        border: true,
        id: 'customerList',
        align: 'center',
        rowConfig: {
          keyField: 'dataId',
          isHover: true
        },
        columnConfig: {
          resizable: true
        },
        customConfig: {
          storage: true,
        },
        toolbarConfig: {
          zoom: true,
          custom: true,
          slots: {
            buttons: 'toolbar_buttons',
          },
          className: 'mytoolbar',
        },
        columns: [
          { type: 'checkbox',
            title: '',
            fixed:'left',
            width: 50,
          },
          {
            field: 'customerName',
            fixed:'left',
            title: '客户名称',
            width: 200,
            slots: {
              // 使用插槽模板渲染
              default: 'num1_default',
            }
          },
          {
            field: 'sonName',
            title: '子客户',
            width: 200,
            slots: {
              // 使用插槽模板渲染
              default: 'num2_default',
            }
          },
          {
            field: 'aboutPerProfit',
            title: '吨毛利',
            width: 100
          },
          {
            field: 'aboutBuyNum',
            title: '月销量',
            width: 100,
          },{
            field: 'customerNewType',
            title: '客户分类',
            width: 100,
          }, {
            field: 'goodsLineNames',
            title: '产品线',
            width: 150,
          },
          {
            field: 'stepName',
            title: '开发阶段',
            width: 100,
          },
          // {
          //   field: 'difficultyName',
          //   title: '难易度',
          //   width: 100,
          // },
          {
            field: 'newNature',
            title: '规模性质',
            width: 100,
          },
          {
            field: 'customerQualityStr',
            title: '客户性质',
            width: 100,
          },
          {
            field: 'newLevel',
            title: '客户级别',
            width: 100,
          },
          // {
          //   field: 'trackingRate',
          //   title: '跟进频次(天)',
          //   width: 100,
          // },
          // {
          //   field: 'visitRate',
          //   title: '拜访频次(天)',
          //   width: 150,
          // },
          {
            field: 'userName',
            title: '客户负责人',
            width: 100,
          },
          {
            field: 'subChargeNames',
            title: '客户协助人',
            width: 150,
          },
          {
            field: 'stepStartTime',
            title: '阶段开发开始时间',
            width: 130,
          },
          {
            field: 'stepEndTime',
            title: '阶段开发结束时间',
            width: 130,
          },
          {
            field: 'diffDays',
            title: '阶段持有天数',
            width: 110,
          },
          {
            field: 'diffChargeDays',
            title: '持有天数',
            width: 110,
          },
          {
            field: 'lastTrackingTime',
            title: '最近跟进时间',
            width: 130,
          },
          {
            field: 'lastVisitTime',
            title: '最近拜访时间',
            width: 130,
          },
          {
            field: 'nextContactTime',
            title: '预计下次跟进时间',
            width: 130,
          },
          {
            field: 'nextVisitTime',
            title: '预计下次拜访时间',
            width: 130,
          },
          {
            field: 'myTrackingNum',
            title: '当前负责人跟进总数',
            width: 130,
          },
          {
            field: 'myContactNum',
            title: '当前负责人日常跟进 ',
            width: 130,
          },
          {
            field: 'myVisitNum',
            title: '当前负责人拜访跟进 ',
            width: 130,
          },
          {
            field: 'myOrderNum',
            title: '当前负责人成交跟进数',
            width: 140,
          },
          {
            field: 'allTrackingNum',
            title: '跟进总数 ',
            width: 130,
          },
          {
            field: 'allContactNum',
            title: '日常跟进总数',
            width: 130,
          },
          {
            field: 'allVisitNum',
            title: '拜访跟进总数',
            width: 130,
          },
          {
            field: 'allOrderNum',
            title: '成交跟进总数',
            width: 130,
          },
          {
            field: 'lastOrderTime',
            title: '最近成交时间',
            width: 130,
          },
          // {
          //   field: 'applyState',
          //   title: '延期状态',
          //   width: 150,
          //   slots: {
          //     // 使用插槽模板渲染
          //     default: 'num3_default',
          //   }
          // },
          // {
          //   field: 'applyReason',
          //   title: '延期原因',
          //   width: 150,
          // },
          {
            field:'inquiryPriceCount',
            title:'本月询盘次数',
            width: 110,
          },
          {
            field:'completeRate',
            title:'客户信息完成度',
            width: 110,
          },
          {
            field:'visitNumPerYear',
            title:'拜访带宽(次/年)',
            width: 110,
          },
          {
            field:'trackingNumPerMonth',
            title:'跟进带宽(次/月)',
            width: 110,
          },
          {
            fixed:'right',
            field: 'distributionStr',
            title: '流转类型',
            width: 130,
          },
          {
            field: 'delayNum',
            title: '延长次数',
            width: 130,
          },
          {
            field: '',
            title: '操作',
            width: 150,
            fixed:'right',
            slots: {
              // 使用 JSX 渲染
              default: 'num4_default',
            },
          },
        ],
        data: [],
      },
      newNatureList:[],
      customerTypeList:[]
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
  },
  created() {
  },
  filters: {
    // fifApply(val) {
    //   if (val == 0) {
    //     return '待提交'
    //   } else if (val == 10) {
    //     return '未审核'
    //   } else if (val == 20) {
    //     return '审核未通过'
    //   }
    // },

  },
  components: {
    cmsTransfer
  },
  methods: {
    moreyc(){
      let list = this.$refs.customerListGrid.getCheckboxReserveRecords();
      let list2 = this.$refs.customerListGrid.getCheckboxRecords();
      let records = JSON.parse(JSON.stringify(list.concat(list2)));
      let customerIds = records.map(item=>item.customerId)
      if(records.length == 0){
        this.$message({type:'error',message:'请先选择客户'})
        return false
      }
      let delayNum = records.filter(item=>item.delayNum >=2)
      console.log(delayNum)
      if(delayNum.length >0){
        let text = `所选客户中有延长次数大于等于2次的客户，请确认!`
        this.$confirm(text, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delayCustomer({customerId:customerIds.join(",")}).then((res) => {
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      }else{
        delayCustomer({customerId:customerIds.join(",")}).then((res) => {
          this.getList()
        })
      }

    },
    //延长
    delay(item){
      if(item.delayNum >=2){
        let text = `该客户已经延长${item.delayNum}次，请确认!`
        this.$confirm(text, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
            this.setDelay(item)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      }else{
        this.setDelay(item)
      }
    },
    //延长api
    setDelay(item){
      delayCustomer({customerId:item.customerId}).then((res) => {
        this.getList()
      })
    },
    //获取客户分类列表
    getCustomerType(){
      getConfigList({status:1}).then((res)=>{
        let customerType = res.find((el)=>{
          return  el.cdtCode == 'customer_new_type'
        })
        this.customerTypeList = customerType ? customerType.data : []
      })
    },
    getnewNatureList(){
      getCustomerInfoAPI({tab:2}).then((res) => {
        this.newNatureList=res;
      })
    },

    //切换省
    changeAreaId1(item) {
      this.areaIndex1 = this.areaList.findIndex((el) => {
        return item == el.areaId
      });
      this.areaIndex2 = null;
      this.listQuery.areaId2 = '';
      this.listQuery.areaId3 = '';
    },
    //切换市
    changeAreaId2(item) {
      this.areaIndex2 = this.areaList[this.areaIndex1]['areaChildList'].findIndex((el) => {
        return item == el.areaId
      });
      this.listQuery.areaId3 = '';
    },
     //显示转移弹窗
    showQuit(row,type) {
      this.$refs.cmsTransfer.showPop(row.customerId,type,row.isCharge);
    },
    init(tab, type) {
      this.listQuery = JSON.parse(JSON.stringify(defaultListQuery))
      this.listQuery.tab = tab;
      this.listQuery.isToday = 0;
      this.listQuery.type = type;
      this.tableData = [];
      this.count = 0;
      this.getList();
      this.getnewNatureList();
      this.getCustomerType()
    },

    //去客户详情页
    toDetail(item) {
      let routeData = this.$router.resolve({name:'customerDetail',query:{id:item.customerId}});
      window.open(routeData.href);
    },

    //客户名称输入匹配
    querySearch(queryString, cb) {
      getCustomerOption({ keywords: queryString }).then((res) => {
        cb(res);
      })
    },


    //选择客户名称
    handleSelectCustomerName(item) {
      this.listQuery.customerName = item.customerName
    },


    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val;
      this.getList();
    },

    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.getList();
    },

    //获取列表
    getList() {
      // this.multipleSelection = [];
      // this.$refs.moreTable.clearSelection()
      this.$refs.customerListGrid.clearCheckboxRow(false);
      this.$refs.customerListGrid.clearCheckboxReserve()
      this.listLoading = true;
      trackingCustomerList(this.listQuery).then(response => {
        this.gridOptions.data = response.list;
        // this.tableData = response.list;
        this.count = response.count;
        this.num = response.num;
        this.listLoading = false;
      }).catch(() => {
        this.listLoading = false;
      });
    },

  },
};
</script>



